# -*- coding = utf-8 -*-
# @Time : 2020/7/19 15:25
# @Author : gxm

import os

import requests

import base64

import json

from pprint import pprint

import time

#client_id 为官网获取的AK， client_secret 为官网获取的SK

api_key = 'gNe4RDL2dVhgtIMlVYT61Lmy'

secret_key = 'T4PfhdHTrM4y1Pj5al7M8SAnp6te7tG1'



class LandmarkRecognizer(object):

    def __init__(self, api_key, secret_key):
        self.access_token = self._get_access_token(api_key=api_key, secret_key=secret_key)
        self.API_URL = 'https://aip.baidubce.com/rest/2.0/image-classify/v1/vehicle_damage' + '?access_token=' \
                       + self.access_token

    #获取token

    @staticmethod

    def _get_access_token(api_key, secret_key):

        api = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials' \
              '&client_id={}&client_secret={}'.format(api_key, secret_key)

        rp = requests.post(api)

        if rp.ok:
            rp_json = rp.json()
            # print(rp_json['access_token'])
            return rp_json['access_token']
        else:
            print('=> Error in get access token!')

    def get_result(self, params):
        rp = requests.post(self.API_URL, data=params)
        if rp.ok:
            print('=> Success! got result: ')
            rp_json = rp.json()
            # pprint(rp_json)
            return rp_json

        else:
            print('=> Error! token invalid or network error!')
            print(rp.content)
            return None

    #车辆损伤识别

    def detect(self, img_path):
        f = open(img_path, 'rb')
        # strover = '识别结果：'
        img_str = base64.b64encode(f.read())
        params = {'image': img_str}
        tic = time.clock()
        rp_json = self.get_result(params)
        toc = time.clock()
        # print(rp_json)
        # print('花费时长: '+'%.2f'  %(toc - tic) +' s')

        parts="损伤位置:"+rp_json['result']['damage_info'][0]['parts']
        type=" 损伤类型:"+ rp_json['result']['damage_info'][0]['type']
        return  parts+type

recognizer = LandmarkRecognizer(api_key, secret_key)

if __name__ == '__main__':


    img = 'C:\\Users\\10975\\Desktop\\22.png'

    str=recognizer.detect(img)
    print(str)
    # print("损伤位置:",str['result']['damage_info'][0]['parts'])
    # print("损伤类型:",str['result']['damage_info'][0]['parts'])